<?php

namespace app\index\service;

use app\common\dao\SettingDao;
use app\common\model\AccessLog;
use app\common\model\Area;
use app\common\model\ConsultingQuestion;
use app\common\model\ConsultingServer;
use app\common\model\ConsultingServerSku;
use app\common\model\Landing;
use app\common\service\ARYPushQueueService;
use app\common\traits\AreaTrait;
use app\index\dao\LandingDao;
use app\index\model\UM as UM;
use think\exception\ValidateException;

/**
 * Class Landing2Service
 * @package app\index\service
 */
class Landing2Service
{
    use AreaTrait;

    // dao
    private LandingDao $landingDao;

    public function __construct(LandingDao $landingDao)
    {
        $this->landingDao = $landingDao;
    }

    /**
     * 落地页2
     * @param UM|null $user
     * @param array $params
     * @return array
     */
    public function read(?UM $user, array $params): array
    {

        $data = [];

        // 服务
        $server = ConsultingServer::where('serverType', ConsultingServer::PHONE)
                                  ->field(['id', 'showPrice', 'price', 'name', 'icon'])
                                  ->withAttr([
                                      'price' => fn($value) => (float)$value,
                                      'showPrice' => fn($value) => (float)$value,
                                  ])
                                  ->append(['iconImg'])
                                  ->find();

        $server->consultingServerSkuId = '0';

        $servers = [];
        $servers[] = $server;

        // 查询SKU
        ConsultingServerSku::where('consultingServerId', $server->id)
                           ->where('deleted', '0')
                           ->withAttr([
                               'price' => fn($value) => (float)$value,
                               'showPrice' => fn($value) => (float)$value,
                           ])
                           ->select()
                           ->each(function (ConsultingServerSku $sku) use (&$servers, $server) {

                               $temp = clone $server;

                               foreach ($temp->getData() as $field => $value) {
                                   if (isset($sku->$field)) {
                                       $temp->$field = $sku->$field;
                                   }
                               }

                               $temp->consultingServerSkuId = $sku->id;
                               $temp->id = $server->id;

                               $servers[] = $temp;
                           });

        $data['server'] = $server;
        $data['servers'] = \think\model\Collection::make($servers);

        return $data;
    }

    /**
     * 填信息
     * @param UM $user
     * @param array $params
     * @return  Landing
     */
    public function add(UM $user, array $params): Landing
    {
        $landingType = 'landing2';

        $memberId = $user->id;
        $phone = $user->phone;

        $moneyId = $params['moneyId'] ?? null;

        $ask = $params['ask'] ?? '';
        $categoryId = 0;
        $provinceId = $params['provinceId'] ?? 0;
        $cityId = $params['cityId'] ?? 0;
        $details = [];
        $detailsValid = details_valid($details);
        $appeal = $params['appeal'] ?? 'analyse';
        $channel = $params['channel'] ?? '';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (!is_id($moneyId)) {
            throw new ValidateException('请选择案件金额');
        }

        ['provinceId' => $provinceId, 'cityId' => $cityId] = $this->completionCity($provinceId, $cityId, $phone);

        // 添加问题
        if (not_blank($ask)) {
            $question = $this->getQuestionService()->saveQuestion($memberId, $ask, $categoryId, ConsultingQuestion::SOURCE_LANDING1, ConsultingQuestion::FROM_LANDING1, false,
                $channel, $pf, $chain, $promotionGroupId);
        } else {
            $question = null;
        }

        $aryMatch = 0;
        if ($pf == AccessLog::PF_H5) {
            $aryMatch = $this->getSettingDao()->getValueByKey('aryMatch', 0);
        }

        // 添加落地页咨询记录
        $caseParams = [
            'landingType' => $landingType,
            'memberId' => $memberId,
            'questionId' => $question ? $question->id : '0',
            'ask' => $ask,
            'categoryId' => $categoryId,
            'moneyId' => $moneyId,
            'provinceId' => $provinceId,
            'cityId' => $cityId,
            'phone' => $phone,
            'status' => 0,
            'appeal' => $appeal,
            'details' => $details,
            'detailsValid' => $detailsValid,
            'channel' => $channel,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
            'aryMatch' => $aryMatch,
        ];
        $record = $this->getLandingDao()->insertActive($caseParams);

        // 延迟推送到案如云
        $this->getARYPushQueueService()->pushLanding($record->id);

        return $record;
    }

    /**
     * 不填信息
     * @param UM $user
     * @param array $params
     * @return  Landing
     */
    public function add2(UM $user, array $params): Landing
    {
        $landingType = 'landing2';

        $memberId = $user->id;
        $phone = $user->phone;

        $provinceId = $params['provinceId'] ?? 0;
        $cityId = $params['cityId'] ?? 0;

        $channel = $params['channel'] ?? '';

        $details = [];
        $detailsValid = details_valid($details);

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        ['provinceId' => $provinceId, 'cityId' => $cityId] = $this->completionCity($provinceId, $cityId, $phone);

        $aryMatch = 0;
        if ($pf == AccessLog::PF_H5) {
            $aryMatch = $this->getSettingDao()->getValueByKey('aryMatch', 0);
        }

        // 添加落地页咨询记录
        $caseParams = [
            'landingType' => $landingType,
            'memberId' => $memberId,
            'questionId' => '0',
            'ask' => '',
            'categoryId' => '0',
            'moneyId' => '0',
            'provinceId' => $provinceId,
            'cityId' => $cityId,
            'phone' => $phone,
            'status' => 0,
            'appeal' => '',
            'details' => $details,
            'detailsValid' => $detailsValid,
            'channel' => $channel,
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
            'aryMatch' => $aryMatch,
        ];
        $record = $this->getLandingDao()->insertActive($caseParams);

        // 延迟推送到案如云
        $this->getARYPushQueueService()->pushLanding($record->id);

        return $record;
    }


    private function completionCity($provinceId, $cityId, $phone)
    {
        if (!is_id($cityId)) {
            ['province' => $province, 'city' => $city] = $this->getProvinceCityByPhone($phone);
            if ($province) {
                $provinceId = $province->id;
            }
            if ($city) {
                $cityId = $city->id;
            }
        }

        if (!is_id($provinceId) && is_id($cityId)) {
            $city = Area::where('id', $cityId)->find();
            if ($city) {
                $provinceId = $city->pid;
            }
        }

        return [
            'provinceId' => $provinceId,
            'cityId' => $cityId,
        ];
    }


    private function getSettingDao(): SettingDao
    {
        return app(SettingDao::class);
    }

    private function getLandingDao(): LandingDao
    {
        return app(LandingDao::class);
    }

    private function getARYPushQueueService(): ARYPushQueueService
    {
        return app(ARYPushQueueService::class);
    }

    private function getQuestionService(): QuestionService
    {
        return app(QuestionService::class);
    }

}
